package org.pettyfox.tool.pm;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import jdk.nashorn.internal.runtime.ECMAException;

import java.io.File;
import java.nio.file.Paths;
import java.util.Date;

public class PasswordMe {
    public String decode(byte[] key,byte[] password){
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);
        return aes.decryptStr(password, CharsetUtil.CHARSET_UTF_8);
    }
    public String encode(byte[] key,byte[] password,String name){
        try{
            SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);
            byte[] p =  aes.encrypt(password);
            File dFile = Paths.get(System.getProperty("user.dir"),"pwd-bin", name).toFile();
            FileUtil.writeBytes(p, dFile);
            return dFile.getAbsolutePath();
        }catch (Exception e){

            e.printStackTrace();
            return "error";
        }

    }
    public String buildKey(){
        byte[] key = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue(),256).getEncoded();
        File dFile = Paths.get(System.getProperty("user.dir"),"key.bin").toFile();
        FileUtil.writeBytes(key, dFile);
        return dFile.getAbsolutePath();
    }
    public static void main(String[] args) {
        System.out.println("Hello World");
        String content = "test中文";

        //随机生成密钥
        byte[] key = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue(),256).getEncoded();
        //
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);

//加密
        byte[] encrypt = aes.encrypt(content);
//解密
        //nihao
        byte[] decrypt = aes.decrypt(encrypt);

//加密为16进制表示
        String encryptHex = aes.encryptHex(content);
//解密为字符串
        String decryptStr = aes.decryptStr(encryptHex, CharsetUtil.CHARSET_UTF_8);
        System.out.println(decryptStr);
    }
}
